package com.flaskpy.web.eternity.core.factory;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.flaskpy.web.eternity.core.cache.RedisForValueCache;
import com.flaskpy.web.eternity.core.cache.abs.ICacheOperation;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @className: RedisConfigFactory
 * @description: 这个人很赖不留下一点说明
 * @author: flaskpy 代码copy大师
 * @date: 2021/6/11
 **/
public class RedisConfigFactory {
    /**
     * 获取取列化对象
     * @param cls
     * @return
     */
    public static FastJsonRedisSerializer generateRedisSerializer(Class<?> cls){

        FastJsonRedisSerializer objSerializer = new FastJsonRedisSerializer(cls);
        objSerializer.getFastJsonConfig().setSerializerFeatures(
                SerializerFeature.WriteMapNullValue,        // 是否输出值为null的字段,默认为false,我们将它打开
                SerializerFeature.WriteNullListAsEmpty,     // 将Collection类型字段的字段空值输出为[]
                //SerializerFeature.WriteNullStringAsEmpty,   // 将字符串类型字段的空值输出为空字符串
                //SerializerFeature.WriteNullNumberAsZero,    // 将数值类型字段的空值输出为0
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.DisableCircularReferenceDetect    // 禁用循环引用
        );
        objSerializer.getFastJsonConfig().setDateFormat("yyyy-MM-dd HH:mm:ss");
        return objSerializer;
    }
    public static<T> ICacheOperation<T> generateCacheOperation(String per,RedisConnectionFactory redisConnectionFactory,Class<T> cls){
        RedisTemplate<String, T> temp = generateRedisTemple(redisConnectionFactory, cls);
        temp.afterPropertiesSet();
        RedisForValueCache<T> result = new RedisForValueCache<T>(per,temp);
        return result;
    }
    public static<T> RedisTemplate<String,T> generateRedisTemple(RedisConnectionFactory redisConnectionFactory,Class<T> cls){
        RedisTemplate<String,T> redisObjectTemplate=new RedisTemplate<>();
        FastJsonRedisSerializer objSerializer =generateRedisSerializer(cls);
        StringRedisSerializer strSerializer = new StringRedisSerializer();

        redisObjectTemplate.setKeySerializer(strSerializer);
        redisObjectTemplate.setHashKeySerializer(strSerializer);
        redisObjectTemplate.setValueSerializer(objSerializer);
        redisObjectTemplate.setHashValueSerializer(objSerializer);
        //开启事务
        redisObjectTemplate.setEnableTransactionSupport(true);
        redisObjectTemplate.setConnectionFactory(redisConnectionFactory);
        return redisObjectTemplate;
    }

}
